var imgdata = {'isconfile':'0','delfileurl':''}

$(function(){
    layui.use(['layer','form', 'table','laytpl', 'upload'], function(){
        var form = layui.form;
        var layer = layui.layer;
        var table = layui.table;
        var laytpl = layui.laytpl;
        var upload = layui.upload;
        
        $.ajaxSetup({
               headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
               }
        });

          table.render({
             elem: '#nevimsg'
             ,url: '/Xadverts' //数据接口
             ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 5 //只显示 1 个连续页码
                ,first: false //不显示首页
                ,last: false //不显示尾页
              }
              ,limit:10 //每页默认显示数
              ,limits:[5,10,20,50,100]
             ,cols: [[ //表头
               {field: 'id', title: 'ID', width:80, sort: true, align:'center'}
               ,{field: 'titles', title: '标题', width:130, align:'center'}
               ,{field: 'pathname', title: '位置', width:130, align:'center', templet: '#path'}
               ,{field: 'urls', title: '链接', width:100, align:'center'}
               ,{field: 'pictures', title: '展示图', width: 150, align:'center', templet: '#img'}
               ,{field: 'create_time', title: '添加时间'}
               ,{field: 'is_show', title:'展示前台',templet: '#ishow', align:'center', templet:function(d){ return d.is_show == 0 ? '<a class="layui-btn  layui-btn-sm layui-btn-warm" lay-event="show" status="0">未展示</a>' : '<a class="layui-btn  layui-btn-sm layui-btn-warm" lay-event="show" status="1">展示中</a>';} ,unresize: true}
               ,{fixed: 'right', title:'编辑', align:'center', toolbar: '#barDemo'}

            ]]
            
          });

       //上传图片
       var uploadPic =  upload.render({
           elem: '.electpic'
          ,url: '/Uploads'
          ,auto: false //选择文件后不自动上传
          ,bindAction: '.addpic' //指向一个按钮触发上传
          ,headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
          ,accept: 'images'
          ,data: imgdata
          ,choose: function(obj){
            obj.preview(function(index, file, result){
              $("#imgadd").attr("src",result);
              $("#imgadd").css('display','block');
              
              $("#imgupdate").attr("src",result);
              $("#imgupdate").css('display','block');
              imgdata['delfileurl'] = $('input[name="imgurl"]').val();
            });
          }
          ,done:function(res, index, upload){
              if (res.code == 200) {
                  $('.imgcurl').val(res.src);
                  layer.msg(res.msg,{time:1000,icon:1}) 
              }
          }
          ,error:function(index, upload){
              $('.chongbutd').css('display','block');
              $('#imgcurl').val('');
              $('#addpic2').click(function(){
                 uploadPic.upload();
              })

          }
        });      

        //添加弹窗
        $(".add-tan").click(function () {
          index = layer.open({
              type: 1,
              title: '新增信息',
              shadeClose: true,
              shade: 0.8,
              area: ['40%', '78%'],
              content: $('.add-data'),
              cancel: function (index, layero) {
                  if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                      $("#imgadd").attr("src",'');
                      $("#imgadd").css('display','none');
                      $('#imgcurl').val('');
                      layer.close(index)
                  }
                return false;
              }
            });
          });

       //添加 监听提交
        form.on('submit(addbutton)', function(data){
              // console.log(data.field);
               $.post('/XadvertAction',data.field,function(obj){
                    //根据返回结果作出相应处理
                    // alert(obj); return false;
                    if (obj.code == 400) 
                    {
                         layer.msg(obj.status+':'+obj.msg)
                    } else {
                         layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                            layer.close('index');
                            location.href = location.href;
                          }) 
                    }
                },'json');
                return false;//注释掉这行代码后，表单将会以普通方式提交表单，否则以ajax方式提交表单

        });


          //监听工具条  删除 修改功能
          table.on('tool(datalist)', function(obj)
          {
            var data = obj.data;
            if(obj.event === 'show')
            {
                  var buttonmsg = $(this);
                  var status = buttonmsg.attr('status');
                  nowstatus = status == 0 ? 1 : 0;
                  var buttontext = buttonmsg.attr('status') == 0 ? '展示中' : '未展示';
                  $.post('/Xisshow', {id:data.id,is_show:nowstatus},function(obj){
                      //根据返回结果作出相应处理
                      if (obj.code == 200) 
                      {
                          layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                              buttonmsg.attr('status',nowstatus);
                              buttonmsg.text(buttontext);
                            }) 
                      } else if(obj.code == 400){
                           layer.msg(obj.status+':'+obj.msg)
                      }
                  },'json');
                  return false;


            } 
            else if (obj.event === 'del') 
            {
              if(confirm('删除后将无法恢复 确定要删除吗？')){ //只有当点击confirm框的确定时，该层才会关闭
                  $.get('/Xadvertdel', {id:data.id},function(objs){
                      //根据返回结果作出相应处理
                      if (objs.code == 200) 
                      {
                          layer.msg(objs.status+':'+objs.msg,{time:1000,icon:1}) 
                          obj.del();
                      } else if(objs.code == 400){
                           layer.msg(objs.status+':'+objs.msg)
                      }
                  },'json');
                  
                  
              }

            }
            else if(obj.event === 'edit')
            {           
                //修改赋值
                form.val('example',{
                        'id' : data.id,
                        'titles' : data.titles,
                        'urls' : data.urls,
                        'advert_path' : data.paths,
                        'imgurl' : data.pictures,
                      });
                $("#imgupdate").css('display','block');
                url_path = $('#hidden_url').val();
                $('#imgupdate').attr('src',url_path+'/'+data.pictures);
                imgdata.delfileurl = data.pictures;  //上传图片赋值imgurl

                //编辑弹窗
                layer.open({
                    type: 1,
                    title: '编辑信息',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['40%', '75%'],
                    content: $('.update-data'),
                    cancel: function (index, layero) {
                      if(confirm('请确定您数据无修改后关闭')){ //只有当点击confirm框的确定时，该层才会关闭
                          layer.close(index)
                      }
                      return false;
                    }
                });

            }
        });

        //修改  监听提交
        form.on('submit(update-button)', function(data){
            // console.log(JSON.stringify(data.field))
            $.post('/XadvertUpdate',data.field,function(obj){
                //根据返回结果作出相应处理
                // alert(obj);return false;
                    if (obj.code == 200) 
                    {
                        layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                            layer.close('edit');
                            location.href = location.href;
                          }) 
                    } else if(obj.code == 400){
                         layer.msg(obj.status+':'+obj.msg)
                    }
            },'json');
            return false;//注释掉这行代码后，表单将会以普通方式提交表单，否则以ajax方式提交表单
                
        });

        laytpl.config({
          open: '<<',
          close: '>>'
        });

          //点击刷新页面
          $(".layui-refresh").click(function () {
               location.href = location.href;
          });
      })
  })
